package com.tanhua.server.service;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.BlossomApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Blossom;
import com.tanhua.model.vo.BlossomVo;
import com.tanhua.model.vo.ErrorResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service
public class BlossomService {
    @DubboReference
    private BlossomApi blossomApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;
    public void saveBlossom(MultipartFile soundFile) throws IOException {

        String upload = ossTemplate.upload(soundFile.getOriginalFilename(),
                soundFile.getInputStream());
        Blossom blossom=new Blossom();
        Long userId = UserHolder.getUserId();
        blossom.setUserId(userId);
        blossom.setSoundUrl(upload);
        blossom.setDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        Integer count=blossomApi.findCount(blossom);
        if(count==4){
            throw new BusinessException(ErrorResult.noTimeError());
        }
        blossomApi.save(blossom);
    }
    public BlossomVo receive() {
        Blossom blossom=new Blossom();
        Long userId = UserHolder.getUserId();
        blossom.setUserId(userId);
        blossom.setDate(new SimpleDateFormat("yyyyMMdd").format(new Date()));
        Integer count= blossomApi.findReceiveCount(blossom);//首先要进行数量的查询
        if(count==3){
            throw new BusinessException(ErrorResult.noTimeError());
        }
        Map map=blossomApi.Random(blossom);//得到的就是剩余的次数
        //返回包装数据
        Object userId1 = map.get("userId");
        if(userId1==null){
            throw new BusinessException(ErrorResult.noBlossomError());
        }
        Long userId2=(Long) userId1;
        if(userId2==-1){
            throw new BusinessException(ErrorResult.noBlossomError());
        }
        UserInfo userInfo = userInfoApi.findById(userId2);
        System.out.println(userId2);
        BlossomVo blossomVo=new BlossomVo();
        //保存的数据是空的
        BeanUtils.copyProperties(userInfo,blossomVo);
        Integer remainingTimes =(Integer)map.get("remainingTimes");
        String soundUrl = (String)map.get("soundUrl");
        blossomVo.setSoundUrl(soundUrl);
        blossomVo.setRemainingTimes(remainingTimes);
        return blossomVo;
    }
}
